from cou.models import *
from pprint import pprint
import json
from cou import db
def cou_manjian_all():
    shops=Shop.query.all()
    for i in shops:
        cou_manjian(i.id)
def cou_manjian(Shop_id):
    shop=Shop.query.filter_by(id=Shop_id).first()
    
    foods=shop.foods
    juans=shop.juans
    manjians=shop.discounts
    for manjian in manjians:
        print("正在凑"+shop.name+":")
        man=manjian.man 
        jian=manjian.jian
        food_list=list()
        total_price=0
        finish_flag=False
        while not finish_flag:
            price_cha=list()
            for i in range(len(foods)):
                price_cha.append(abs(man-total_price-foods[i].price))
            next_food_index=price_cha.index(min(price_cha))
            food_list.append(foods[next_food_index])
            total_price+=foods[next_food_index].price
            if total_price>=man:
                finish_flag=True
        temp_set=set(food_list)
        
        food_num=dict()
        for i in temp_set:
            num=list.count(food_list,i)
            food_num[str(i.id)]=num
        food_list=list(temp_set)
        juan=Juan.query.filter(Juan.man<=total_price).order_by(Juan.jian).first()
        jian+=juan.jian
        temp_taocan=Taocan()
        temp_taocan.name="{}元套餐".format((total_price-jian)/100)
        temp_taocan.discount=int(((total_price-jian)/total_price)*100)
        temp_taocan.price=((total_price-jian))
        temp_taocan.foods=food_list
        temp_taocan.foods_info=json.dumps(food_num)
        temp_taocan.shop_id=Shop_id
        temp_taocan.manjian_id=manjian.id
        temp_taocan.juan_id=juan.id
        temp_taocan.area_id=shop.area_id
        db.session.add(temp_taocan)
        db.session.commit()




            



